package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.DataManager;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.widget.MsgView;
import com.epfresh.api.widget.MultipleStatusView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.tablayout.SlidingTabLayout;
import com.epfresh.api.widget.tablayout.listener.OnTabSelectListener;
import com.epfresh.api.widget.tablayout.utils.UnreadMsgUtils;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.CategoryListViewBinder;
import com.epfresh.supplier.adapter.GoodsListViewBinder;
import com.epfresh.supplier.dialog.CustomDetailDeleteDialog;
import com.epfresh.supplier.dialog.InventoryEditDialog;
import com.epfresh.supplier.entity.Category;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.Goods;
import com.epfresh.supplier.entity.PriceNoticeEntity;
import com.epfresh.supplier.entity.StatusEntity;
import com.epfresh.supplier.widget.WrapContentLinearLayoutManager;
import com.google.gson.Gson;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;
public class ChangePriceActivity extends BaseActivity {

    private SlidingTabLayout lyTab;

    private View tabLine;
    private MultipleStatusView msvContent;
    private MultipleStatusView msvGoods;
    MultiTypeAdapter mCategoryAdapter;
    CategoryListViewBinder mCategoryBinder;
    RecyclerView rvCategory;

    List<Category> mCategorise = new ArrayList<>();
    List<Category> list = new ArrayList<>();

    String topCategoryId = null;
    String topCategoryType = null;
    String categoryId = null;
    String categoryType = null;

    View vNotice;
    TextView tvNotice;
    ImageView ivNotice;
    MsgView msgView;
    protected View getToolBarView() {
        View view = inflaterView(R.layout.toolbar_change_price, null);
        msgView = (MsgView) view.findViewById(R.id.msg_cnt);
        return view;
    }

    //刷新变加提交的数量
    public void updateMsgCnt(int cnt){
        UnreadMsgUtils.showLitter(msgView,cnt,false,true);
    }


    public void updateCnt(){
        Map<String, Integer> mapTC = new HashMap<>();
        Map<String, Integer> mapC = new HashMap<>();
        int cnt = 0;
        for (String key : DataManager.getInstance().mapPriceGoods.keySet()) {
            cnt ++;
            Goods priceGoods = DataManager.getInstance().getPriceGoods(key);

            String kT = priceGoods.getKeyTop();
            if (kT != null && !"".equals(kT)) {
                Integer integer = mapTC.get(kT);
                integer = integer == null ? 1 : integer+1;
                mapTC.put(kT, integer);
            }
            String k = priceGoods.getKeyTwo();
            if (k != null && !"".equals(k)) {
                Integer integer = mapC.get(k);
                integer = integer == null ? 1 : ++integer;
                mapC.put(k, integer);
            }
        }
        //是否是一级
        if (BaseApplication.getInstance().isCategoryLevelOne()) {
            //一级

            mapC = mapTC;


        } else {

            for (int i=0;i<list.size();i++){
                Category category = list.get(i);
                String key = category.getKey();
                if (key != null && !"".equals(key) && topCategoryId != null&& !topCategoryId.equals(category.getId())) {
                    Integer integer = mapTC.get(key);
                    integer = integer == null ? 0 : integer;
                    lyTab.showMsgLitter(i,integer);
                }else {
                    lyTab.showMsgLitter(i,0);
                }
            }
        }
        Category categoryAll = null;
        int cntAll = 0;
        for (int i = 0; i < mCategorise.size(); i++) {
            Category category = mCategorise.get(i);

            String key = category.getKey();
            String id = category.getId();
            if ("|".equals(key) && (id == null || "".equals(id))) {
                categoryAll = category;
            }

            if (key != null && !"".equals(key)) {
                Integer integer = mapC.get(key);
                category.setCnt(integer == null ? 0 : integer);
                if (integer != null && integer > 0)
                    cntAll++;
            }else {
                category.setCnt(0);
            }

        }

        if (categoryAll != null) {
            categoryAll.setCnt(cntAll);
        }
        mCategoryAdapter.notifyDataSetChanged();
        updateMsgCnt(cnt);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_price);

        toolbarTitle.setText("变价");
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);
        rightbtn.setVisibility(View.VISIBLE);
        rightbtn.setText("变价提交");
        rightbtn.setTextColor(0xff626262);
        rightbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                intoPriceSure();
            }
        });

        //初始化view
        initView();
        //加载数据
        initNotice();
        reqCategoryList();
    }

    private void intoPriceSure() {
        if(DataManager.getInstance().getPriceGoods()==null||DataManager.getInstance().getPriceGoods().size()==0){//有变价格，去确认页面；没有变化，调接口刷新
            Log.e("changePrice","________________"+DataManager.getInstance().getPriceGoods().size());
            if(list==null||list.size()==0)
                return;
            submit();
        }else{
            Intent intent = new Intent(this,PriceSureActivity.class);
            startActivityForResult(intent,0x001);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == 0x001) {
            /*reqCategoryList();
            initNotice();*/
            finish();
        }else{
            updateCnt();/*刷新提示数据*/
            if(mGoodsAdapter!=null)
                mGoodsAdapter.notifyDataSetChanged();
            if(mCategoryAdapter!=null)
                mCategoryAdapter.notifyDataSetChanged();
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }



    private void initView() {
        vNotice = findViewById(R.id.rl_notice);
        tvNotice = (TextView) findViewById(R.id.tv_notice);
        ivNotice = (ImageView) findViewById(R.id.iv_notice);

        vNotice.setVisibility(View.GONE);
        ivNotice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vNotice.setVisibility(View.GONE);
            }
        });



        rvCategory = (RecyclerView) findViewById(R.id.rv_category);
        rvGoods = (RecyclerView) findViewById(R.id.rv_goods);
        lyTab = (SlidingTabLayout) findViewById(R.id.ly_top);
        tabLine = findViewById(R.id.v_tab_line);
        msvContent = (MultipleStatusView) findViewById(R.id.msv_category_content);

        msvGoods = (MultipleStatusView) findViewById(R.id.msv_goods);


        LinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvCategory.setLayoutManager(layoutManager);
        mCategoryAdapter = new MultiTypeAdapter();
        mCategoryBinder = new CategoryListViewBinder();

        mCategoryAdapter.register(Category.class, mCategoryBinder);
        rvCategory.setAdapter(mCategoryAdapter);
        mCategoryAdapter.setItems(mCategorise);
        mCategoryBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int i, Object o) {
                updateCategoryStatus(i);
                mCategoryAdapter.notifyDataSetChanged();
                if (o != null && o instanceof Category) {
                    pageNum = 0;
                    if (mGoods.size() > -1)
                        layoutManagerGoods.scrollToPosition(0);
                    items.clear();
                    mGoods.clear();
//                    mGoodsAdapter.notifyDataSetChanged();
                    updateGoods(0, (Category) o);
                }
            }
        });
        lyTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int i) {
                if (i < list.size()){
                    Category category = list.get(i);
                    if (category != null) {
                        topCategoryType = category.getType();
                        topCategoryId = category.getId();
                        updateCategory(category.getItem());
                        updateCnt();
                    }
                }
            }

            @Override
            public void onTabReselect(int i) {

            }
        });

        msvContent.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reqCategoryList();
            }
        });
        initGoodsView();
    }


    public void updateNotice(String s){
        if("".equals(s)){
            vNotice.setVisibility(View.GONE);
            return;
        }
        tvNotice.setText(s);
        vNotice.setVisibility(View.VISIBLE);
    }


    RecyclerView rvGoods;
    MultiTypeAdapter mGoodsAdapter;
    GoodsListViewBinder mGoodsBinder;
    LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();
    List<Object> items = new ArrayList<>();
    List<Goods> mGoods = new ArrayList<>();
    Goods currentGood;
    int pageNum = 0;
    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rvGoods, header) /*&& !loadMoreDelegate.isLoading()*/;
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            if (!loadMoreDelegate.isLoading()) {

                reqGoodsList(0);
            } else {
                ptrFrameLayout.refreshComplete();
            }
        }
    };
    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();

            reqGoodsList(pageNum + 1);
        }
    };

    private void initHeadView() {
        ptrFrameLayout = (PtrFrameLayout) findViewById(R.id.ptr_ff);
        ptrFrameLayout.setPtrHandler(ptrHandler);
//        ptrFrameLayout.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                ptrFrameLayout.autoRefresh(true);
//            }
//        }, 200);
    }

    private BigDecimal getUnit(Goods goods){
        BigDecimal unit;
        if(goods.getPrice()*10%1>0){
            unit = new BigDecimal(0.01);
        }else if(goods.getPrice()*10%10>0){
            unit = new BigDecimal(0.1);
        }else{
            unit = new BigDecimal(1);
        }
        return unit;
    }

    LinearLayoutManager layoutManagerGoods;
    private void initGoodsView() {

        initHeadView();
        rvGoods = (RecyclerView) findViewById(R.id.rv_goods);
        layoutManagerGoods = new WrapContentLinearLayoutManager(this);
        layoutManagerGoods.setOrientation(LinearLayoutManager.VERTICAL);
        rvGoods.setLayoutManager(layoutManagerGoods);
        mGoodsAdapter = new MultiTypeAdapter();
        mGoodsBinder = new GoodsListViewBinder();
        mGoodsBinder.setOnTextChangerListener(new GoodsListViewBinder.OnTextChangerListener() {
            @Override
            public void onChange() {
                updateCnt();/*刷新提示数据*/
            }
        });
        mGoodsBinder.setOnUpdateListener(new GoodsListViewBinder.OnUpdateListener() {
            @Override
            public void onUpdate(int position, Goods goods) {

                openUpdateDialog(position, goods);
            }

        });
        mGoodsBinder.setOnGroupListener(new GoodsListViewBinder.OnGroupListener() {
            @Override
            public void onGroup(int position, Goods goods) {
                intoGroup(position,goods);
            }
        });
        mGoodsBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if(data instanceof Goods){
                    Goods goods = (Goods) data;
                    BigDecimal unit = getUnit(goods);
                    if(goods.getPriceNow()==null)
                        goods.setPriceNow(goods.getPrice());
                    if(view.getId()==R.id.iv_add){

                        goods.setPriceNow(unit.add(new BigDecimal(goods.getPriceNow())).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
                        if(goods.getPriceNow().doubleValue()>99999.99){
                            toast("价格不能大于99999.99");
                            goods.setPriceNow(99999.99);
                        }
                        if(goods.getPriceNow().doubleValue() == goods.getPrice().doubleValue()){
                            goods.setPriceNow(null);
                            DataManager.getInstance().removePriceGoods(goods.getId());
                            Log.e("add_remove","remove");
                        }else{
                            DataManager.getInstance().putPriceGoods(goods.getId(),goods);
                            Log.e("add_","add");
                        }
                    }else{
                        if(goods.getPriceNow().doubleValue()==0){
                            toast("价格不能小于0");
                            return;
                        }
                        goods.setPriceNow((new BigDecimal(goods.getPriceNow()).subtract(unit)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
                        if(goods.getPriceNow().doubleValue() == goods.getPrice().doubleValue()){
                            goods.setPriceNow(null);
                            DataManager.getInstance().removePriceGoods(goods.getId());
                            Log.e("minus_remove","remove");
                        }else{
                            DataManager.getInstance().putPriceGoods(goods.getId(),goods);
                            Log.e("minus_","add");
                        }
                    }
                    updateCnt();/*刷新提示数据*/
                    mGoodsAdapter.notifyDataSetChanged();
                }
            }
        });

        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
//        loadMoreViewBinder.setPaddingBottom(LocalDisplay.dp2px(65.5f));
        mGoodsAdapter.register(Goods.class, mGoodsBinder);
        mGoodsAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        rvGoods.setAdapter(mGoodsAdapter);
        mGoodsAdapter.setItems(items);

        loadMoreDelegate.attach(rvGoods, loadMoreSubject);
    }

    private void intoGroup(int position, Goods goods) {
        Intent intent = new Intent(this,PriceGroupActivity.class);
        intent.putExtra("price",""+goods.getPrice());
        intent.putExtra("productId",goods.getId());
        intent.putExtra("productUnit",goods.getPriceUnitStr());
        startActivity(intent);
    }

    InventoryEditDialog inventoryEditDialog;
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = formatter.format(currentTime);
    private void openUpdateDialog(int position, final Goods goods) {
        inventoryEditDialog = new InventoryEditDialog(this,goods);
        inventoryEditDialog.setOnSureListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(v.getTag(R.id.item_key_position)!=null&&v.getTag(R.id.item_key_position) instanceof String){
                    if("".equals(v.getTag(R.id.item_key_position).toString())){
                        toast("请输入必填信息");
                        return;
                    }
                    try {
                        Double.parseDouble(v.getTag(R.id.item_key_position).toString());//
                    } catch (Exception ex) {
                        toast("请输入必填信息");
                        return;
                    }

                    double flag = new BigDecimal(v.getTag(R.id.item_key_position).toString()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                    if(flag>99999.99){
                        toast("数量不能大于99999.99");
                        return;
                        //goods.setPriceNow(99999.99);
                    }

                    RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
                    RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_purchase_add);
                    RequestEntityMapSupply.putParameter("productSpecId",goods.getId());
                    RequestEntityMapSupply.putParameter("arrivalDate",dateString);
                    RequestEntityMapSupply.putParameter("upstreamMarket",v.getTag(R.id.item_key_status).toString());
                    RequestEntityMapSupply.putParameter("origin",v.getTag(R.id.item_key_id).toString());
                    RequestEntityMapSupply.putParameter("quantity",v.getTag(R.id.item_key_position).toString());
                    //Log.e("数量 来源地 上游",v.getTag(R.id.item_key_status).toString().toString()+"_"+v.getTag(R.id.item_key_id).toString()+v.getTag(R.id.item_key_position).toString());
                    request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_purchase_add, updateRequestListener);
                }else {
                    toast("请输入必填信息");
                }
            }
        });
        inventoryEditDialog.show(position, goods);
    }

    OnRequestListener<StatusEntity> updateRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {


        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {


        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            if (response != null){
                toast("已更新进货");
                reqCategoryList();
                inventoryEditDialog.dismiss();
            }
        }
    };

    @Override
    protected void onPause() {
        setResult(0x001,new Intent());
        super.onPause();
    }



    private void updateGoods(int pageNum, Category category) {

        //清空分类请求商品数据
        categoryId = null;
        categoryType = null;

        //是否是一级
        if (BaseApplication.getInstance().isCategoryLevelOne()) {
            topCategoryId = category.getId();
            topCategoryType = category.getType();
        } else {
            categoryId = category.getId();
            categoryType = category.getType();
        }
        reqGoodsList(pageNum);

    }

    protected void updateGoodsList(ContentEntity<Goods> ce, Object tag) {
        int number = ce.getNumber();
        boolean last = ce.getLast();

        List<Goods> goodsItems = ce.getContent();

        pageNum = number;
        if (number == 0) {
            items.clear();
            mGoods.clear();
        }
        if (goodsItems != null && goodsItems.size() > 0) {
            mGoods.addAll(goodsItems);
            loadMoreDelegate.addAllItem(items, goodsItems);
            //最后一个
            if (last) {
                loadMoreDelegate.setStatusNoMore();
            } else {
                loadMoreDelegate.setStatusNormal();
            }
            loadGoodsContent();
            mGoodsAdapter.notifyDataSetChanged();
        } else {//没有数据
            loadGoodsEmpty();
        }
    }

/*
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.ba:

                break;
            case R.id.rl_pre_sales:

                break;
        }
    }*/

    protected void loadGoodsError() {
        if (mGoods.size() == 0)
            msvGoods.showError();
    }

    protected void loadGoodsEmpty() {
        msvGoods.showEmpty();
    }

    protected void showGoodsLoading() {
        if (mGoods.size() == 0) {
            msvGoods.showLoading();
        } else {
            msvGoods.showContent();
        }
    }

    protected void loadGoodsContent() {

        msvGoods.showContent();

    }

    protected void loadCategoryError() {
        msvContent.showError();
    }

    protected void loadCategoryEmpty() {
        msvContent.showEmpty();
    }

    protected void showCategoryLoading() {
        msvContent.showLoading();
    }
    protected void loadCategoryContent() {
        msvContent.showContent();
    }

    protected void loadCategory(List<Category> list) {

        if (list == null || list.size() == 0) {
            loadCategoryEmpty();

        } else {
            loadCategoryContent();


            //是否是一级
            if (BaseApplication.getInstance().isCategoryLevelOne()) {
                //一级
                updateCategoryTitle(null);
                lyTab.setVisibility(View.GONE);
                tabLine.setVisibility(View.GONE);
                updateCategory(list);
            } else {
                //二级
                updateCategoryTitle(list);
                lyTab.setVisibility(View.VISIBLE);
                tabLine.setVisibility(View.VISIBLE);
                Category category = null;
                List<Category> children = null;
                if (list.size() > 0) {
                    category = list.get(0);
                    if (category != null) {
                        children = category.getItem();
                    }
                }
                updateCategory(children);

            }
        }

    }


    //一级分类
    private void updateCategoryTitle(List<Category> list) {

        String[] titles = null;
        if (list != null && list.size() > 0) {
            int len = list.size();
            titles = new String[len];
            for (int i = 0; i < len; i++) {
                Category c = list.get(i);
                if (c != null) {
                    if (i == 0) {
                        topCategoryId = c.getId();
                        topCategoryType = c.getType();

                    }
                    titles[i] = c.getName();
                    if (titles[i] == null) {
                        titles[i] = "";
                    }
                } else {
                    titles[i] = "";
                }
            }
        } else {

            titles = new String[0];
        }

        lyTab.setTitles(titles);
        if (titles.length > 0) {
            lyTab.setCurrentTab(0);
        }
    }


    //更新二级分类
    protected void updateCategory(List<Category> list) {
        mCategorise.clear();
        if (list != null && list.size() > 0) {
            mCategorise.addAll(list);
            updateCategoryStatus(0);

            if (mGoods.size() > -1)
                layoutManagerGoods.scrollToPosition(0);
            items.clear();
            mGoods.clear();

            mGoodsAdapter.notifyDataSetChanged();
            pageNum = 0;
            updateGoods(pageNum, list.get(0));

        } else {
            //没有二级分类

            items.clear();
            mGoodsAdapter.notifyDataSetChanged();
        }
        mCategoryAdapter.notifyDataSetChanged();
    }

    public void updateCategoryStatus(int position) {

        for (int i = 0; i < mCategorise.size(); i++) {
            Category o = mCategorise.get(i);
            if (o != null) {
                if (position == i) {
                    o.setSelect(true);
                } else {
                    o.setSelect(false);
                }
            }
        }
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }
    private void reqCategoryList() {

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_store_category_tree4supplier);

        RequestEntityMapSupply.putParameter("storeId",BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("merchantId",BaseApplication.getInstance().getMerchantId());

        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_store_category_tree4supplier, onCategoryRequestListener);
    }

    private OnRequestListener<List<Category>> onCategoryRequestListener = new OnRequestListener<List<Category>>() {
        @Override
        public List<Category> jsonToObj(String responseStr) {

            return JsonUtils.fromJsonObject(responseStr, List.class, Category.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            System.out.println();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            System.out.println();

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<List<Category>> response, Object tag) {

            if (response != null){
                List<Category> responseElement = response.getResponseElement();
                list.clear();
                list.addAll(responseElement);
                loadCategory(responseElement);
                updateCnt();/*刷新提示数据*/
            }
        }
    };

    private void reqGoodsList(int pageNumber) {
        reqGoodsList(pageNumber, null);
    }

    private void reqGoodsList(int pageNumber, List<String> ids) {

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_store_product_list4changePrice);

        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("merchantId", BaseApplication.getInstance().getMerchantId());
        RequestEntityMapSupply.putParameter("topCategoryId", topCategoryId);
        RequestEntityMapSupply.putParameter("topCategoryType", topCategoryType);
        RequestEntityMapSupply.putParameter("categoryId", categoryId);
        RequestEntityMapSupply.putParameter("categoryType", categoryType);
        RequestEntityMapSupply.putParameter("pageNumber", pageNumber);
        RequestEntityMapSupply.putParameter("ids", ids);
        RequestEntityMapSupply.putParameter("pageSize", 15);
        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_store_product_list4changePrice, onGoodsRequestListener);
    }

    private OnRequestListener<ContentEntity<Goods>> onGoodsRequestListener = new OnRequestListener<ContentEntity<Goods>>() {
        @Override
        public ContentEntity<Goods> jsonToObj(String responseStr) {

            return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, Goods.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

            ptrFrameLayout.refreshComplete();

            loadGoodsError();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            ptrFrameLayout.refreshComplete();

            loadGoodsError();

        }

        @Override
        public void onStart(Object tag) {


            showGoodsLoading();

        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<Goods>> response, Object tag) {
            ptrFrameLayout.refreshComplete();
            if (response != null) {
                ContentEntity<Goods> responseElement = response.getResponseElement();
                updateGoodsList(responseElement, tag);

            }
        }
    };

    class PriceModel{
        String id;
        String price;
        public PriceModel(String id,String price){
            this.id = id;
            this.price = price;
        }
    }


    private void submit() {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_store_product_submitPrice);
        RequestEntityMapSupply.putParameter("storeId",BaseApplication.getInstance().getStoreId());
        if(DataManager.getInstance().getPriceGoods()!=null) {
            ArrayList list = new ArrayList();
            for (int i = 0; i < DataManager.getInstance().getPriceGoods().size(); i++) {
                PriceModel priceModel = new PriceModel(DataManager.getInstance().getPriceGoods().get(i).getId(),""+DataManager.getInstance().getPriceGoods().get(i).getPriceNow());
                list.add(priceModel);
            }
            RequestEntityMapSupply.putParameter("prices",list);
        }else{
            RequestEntityMapSupply.putParameter("prices",new ArrayList<>());
        }
        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_store_product_submitPrice, onSubmitRequestListener);
    }

    OnRequestListener<StatusEntity> onSubmitRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {


        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {


        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            if (response != null){
                DataManager.getInstance().clearPriceGoods();
                StatusEntity responseElement = response.getResponseElement();
                toast("已更新价格");
                finish();
                //reqCategoryList();
                //initNotice();
            }
        }
    };

    @Override
    public void onDestroy(){
        super.onDestroy();
        DataManager.getInstance().clearPriceGoods();
    }


    void initNotice(){
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_noticeWord);
        RequestEntityMapSupply.putParameter("storeId",BaseApplication.getInstance().getStoreId());
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_noticeWord, noticeRequestListener);

    }


    OnRequestListener<PriceNoticeEntity> noticeRequestListener = new OnRequestListener<PriceNoticeEntity>() {
        @Override
        public PriceNoticeEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, PriceNoticeEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {


        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {


        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<PriceNoticeEntity> response, Object tag) {
            SharedPreferences sp = getSharedPreferences("notice_time", Context.MODE_PRIVATE);
            if (response != null){
                DataManager.getInstance().clearPriceGoods();
                PriceNoticeEntity responseElement = response.getResponseElement();
                if(responseElement.isShow()) {
                    if (!"".equals(responseElement.getUpdateMessage())) {
                        updateNotice(responseElement.getUpdateMessage());
                    }else{
                        updateNotice("");
                    }
                }else{
                    if (!"".equals(responseElement.getUpdateMessage()) && !sp.getString("show_flag", "1").equals(dateString)) {
                        updateNotice(responseElement.getUpdateMessage());
                        sp.edit().putString("show_flag", dateString).commit();
                    }else{
                        updateNotice("");
                    }
                }
            }
        }
    };

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            baseback.performClick();
        }
        return false;
    }

    private CustomDetailDeleteDialog deleteDialog;
    void back(){
        if(deleteDialog == null)
            deleteDialog = new CustomDetailDeleteDialog(this, true);
        deleteDialog.setMessage("确定放弃当前商品调价吗？");
        deleteDialog.setOnPositiveClickListener("确定", new CustomDetailDeleteDialog.onPositiveClickListener() {
            @Override
            public void onPositiveClickListener() {
                deleteDialog.dismiss();
                finish();
            }
        });
        deleteDialog.setOnNegativeClickListener("取消", new CustomDetailDeleteDialog.onNegativeClickListener() {
            @Override
            public void onNegativeClickListener() {
                deleteDialog.dismiss();
            }
        });
        deleteDialog.show();
    }

    protected void onToolbarBack() {
        if(DataManager.getInstance().getPriceGoods()==null||DataManager.getInstance().getPriceGoods().size()==0) {//有变价格，去确认页面；没有变化，调接口刷新
            finish();
        }else{
            back();
        }
    }
}
